<?php


namespace App\Services\Agora;
require_once(dirname(__FILE__) . "/lib/src/RtcTokenBuilder.php");

class RtcTokenService extends BaseService
{
    private $expireTimeInSeconds = 86400;//令牌过期时间

    /**
     * 生成频道 token
     * @param int $uid 用户ID，不建议直接使用应用id
     * @param string $channelName 频道名称
     * @param int $type 1使用数字uid 2使用字符串 uid
     * @param int $role 用户权限，分为发流用户和接收用户。参数决定用户是否能在频道中发流。该参数仅在开启连麦鉴权后才生效
        Role_Publisher(1)：（默认）用户有发流权限，即用户可在频道中发流。
        Role_Subscriber(2)：用户有接收权限，即用户可在频道中接收，但不可发流。
     * @return string
     */
    public function get($uid, $channelName, $type = 1, $role = null)
    {
        if (!isset($role)) {
            $role = \RtcTokenBuilder::RoleAttendee;
        }
        if ($type == 1) {
            $token = $this->getByUid($uid, $channelName, $role);
        } else {
            $token = $this->getByAccount($uid, $channelName, $role);
        }
        return [
            'userid' => $uid,
            'appid' => $this->appid,
            'token' => $token,
            'timestamp' => time() + $this->expireTimeInSeconds,
            'channel' => $channelName,
        ];
    }

    /**
     * 设置过期时间
     * @param $expire_in 多久过期，单位秒
     * @author an
     * @time 2021-12-07 15:41
     */
    public function setExpireTime($expire_in)
    {
        $this->expireTimeInSeconds = $expire_in;
    }

    //Token with int uid
    private function getByUid($uid, $channelName, $role)
    {
//        $uid = 666;
        $currentTimestamp = (new \DateTime("now", new \DateTimeZone('UTC')))->getTimestamp();
        $privilegeExpiredTs = $currentTimestamp + $this->expireTimeInSeconds;
        $token = \RtcTokenBuilder::buildTokenWithUid($this->appid, $this->appCertificate, $channelName, $uid, $role, $privilegeExpiredTs);
        return $token;
    }

    //Token with user account
    private function getByAccount($uidStr, $channelName, $role)
    {
//        $uidStr = "2882341273"
        $currentTimestamp = (new \DateTime("now", new \DateTimeZone('UTC')))->getTimestamp();
        $privilegeExpiredTs = $currentTimestamp + $this->expireTimeInSeconds;
        $token = \RtcTokenBuilder::buildTokenWithUserAccount($this->appid, $this->appCertificate, $channelName, $uidStr, $role, $privilegeExpiredTs);
        return $token;
    }
}
